package com.jkgl.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jkgl.common.core.domain.entity.SysUser;
import com.jkgl.entity.UserInfoDayEntity;
import com.jkgl.entity.UserInfoSelfEntity;
import com.jkgl.system.service.ISysUserService;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
@Slf4j
public class DayDataCreateService {
    private final UserInfoDayService dayService;
    private final ISysUserService userService;
    private final UserInfoSelfService selfService;

    @XxlJob("DayDataCreate")
    public void dataCreate() {
        QueryWrapper<SysUser> userQuery = new QueryWrapper<>();
        userQuery.lambda().eq(SysUser::getDelFlag, 0);
        List<Long> collect = userService.list(userQuery).stream().map(SysUser::getUserId).collect(Collectors.toList());
//        int temp = 1;
//        while(temp <=10) {
            for (Long userId : collect) {
                if (userId != 1L) {
                    int i = new Random().nextInt(100);
                    log.info("开始{}", userId);
                    if (i < 10) {
                        continue;
                    }
                }
                UserInfoDayEntity day = new UserInfoDayEntity();
                QueryWrapper<UserInfoSelfEntity> selfQuery = new QueryWrapper<>();
                selfQuery.lambda().eq(UserInfoSelfEntity::getUserId, userId);
                UserInfoSelfEntity one = selfService.getOne(selfQuery);
//                day.setCreateTime(LocalDate.now().plusDays(temp));
                day.setCreateTime(LocalDate.now());
                day.setUserId(userId);
//            day.setBloodPressure(bloodPerssure());
                day.setWeightDiff(weightDiff(one.getWeight()));
                day.setStepNumber(targetStep());
                day.setWaterVolume(waterVolume());
                generateBloodPressure(day); // 生成血压数据
                day.setSportTimeLong(generateSportTimeLong()); // 生成运动时长
                timeAndCreate(day);
            }
//            temp++;
//        }
    }

    public String weightDiff(String baseWeight) {
        Random random = new Random();
        // 加减 0.5 到 2 kg，保留2位小数
        double diff = Double.parseDouble(baseWeight) + (random.nextDouble() * 1.5 - 0.75);
        return String.format("%.2f", diff);
    }

    public String bloodPerssure() {
        Random random = new Random();
        // 90 到 140，保留整数
        int systolic = 90 + random.nextInt(51);
        // 60 到 90，保留整数
        int diastolic = 60 + random.nextInt(31);
        return systolic + "/" + diastolic;
    }

    public String targetStep() {
        Random random = new Random();
        // 0 到 20000 之间的随机数
        return String.valueOf(random.nextInt(20001));
    }

    public String waterVolume() {
        Random random = new Random();
        // 1.0 到 3.0 升之间的随机数，保留2位小数
        double volume = 1.0 + random.nextDouble() * 2.0;
        return String.format("%.2f", volume);
    }

    // 修改后的睡眠时间生成（保持原有逻辑）
    public void timeAndCreate(UserInfoDayEntity day) {
        Random random = new Random();
        LocalDateTime now = LocalDateTime.now();

        // 入睡时间（21:00-02:00）
        int sleepHour = 21 + random.nextInt(6);
        if (sleepHour >= 24) {
            sleepHour -= 24;
        }
        LocalDateTime sleepTime = now.with(LocalTime.of(sleepHour, random.nextInt(60), 0));

        // 起床时间（02:00-10:00）
        int wakeHour = 2 + random.nextInt(9);
        LocalDateTime wakeTime = now.with(LocalTime.of(wakeHour, random.nextInt(60)));

        // 处理跨天和睡眠时长
        if (sleepTime.isAfter(wakeTime)) {
            sleepTime = sleepTime.minusDays(1);
        }
        while (sleepTime.plusHours(3).isAfter(wakeTime)) {
            wakeTime = sleepTime.plusHours(3 + random.nextInt(7));
        }

        // 计算睡眠比例（保持原有逻辑）
        double totalHours = (wakeTime.toLocalTime().toSecondOfDay() -
                sleepTime.toLocalTime().toSecondOfDay()) / 3600.0;
        if (totalHours < 0) totalHours += 24;

        // 睡眠阶段分配
        double deep = 15 + random.nextDouble() * 10;
        double rem = 20 + random.nextDouble() * 10;
        double light = 100 - deep - rem;

        // 比例修正
        if (light < 40) {
            double adjust = (40 - light) / 2;
            deep -= adjust;
            rem -= adjust;
            light = 100 - deep - rem;
        }

        day.setDeepSleepPercentage(Double.parseDouble(String.format("%.2f", deep)));
        day.setLightSleepPercentage(Double.parseDouble(String.format("%.2f", light)));
        day.setRemSleepPercentage(Double.parseDouble(String.format("%.2f", rem)));
        day.setSleepTime(sleepTime);
        day.setWakeupTime(wakeTime);

        dayService.create(day);
    }


    // 新增血压生成逻辑
    private void generateBloodPressure(UserInfoDayEntity day) {
        // 生成收缩压
        int sbp;
        Random random = new Random();
        if (random.nextDouble() < 0.9) { // 90%正常范围
            sbp = 90 + random.nextInt(51); // 90-140
        } else { // 10%异常
            sbp = random.nextBoolean() ?
                    141 + random.nextInt(40) : // 偏高141-180
                    70 + random.nextInt(20);    // 偏低70-89
        }

        // 生成舒张压并确保小于收缩压
        int dbp;
        if (random.nextDouble() < 0.9) { // 90%正常范围
            int maxNormal = Math.min(90, sbp - 1);
            dbp = maxNormal < 60 ?
                    random.nextInt(sbp - 60) + 60 : // 处理极低收缩压情况
                    random.nextInt(maxNormal - 59) + 60;
        } else { // 10%异常
            if (random.nextBoolean()) { // 50%概率偏低
                dbp = random.nextInt(10) + 50; // 50-59
                dbp = Math.min(dbp, sbp - 1); // 确保小于收缩压
            } else { // 50%概率偏高
                int minHigh = 91;
                dbp = sbp > minHigh ?
                        random.nextInt(sbp - minHigh) + minHigh :
                        random.nextInt(90 - 60) + 60; // 收缩压不足时回退正常值
            }
        }

        day.setSbp(sbp);
        day.setDbp(dbp);
    }

    // 新增运动时长生成
    private double generateSportTimeLong() {
        double hours;
        Random random = new Random();
        if (random.nextDouble() < 0.9) { // 90%正常范围
            hours = random.nextDouble() * 3.0; // 0.0-3.0小时
        } else { // 10%异常
            hours = 3.0 + random.nextDouble() * 2.0; // 3.0-5.0小时
        }
        return Math.round(hours * 100) / 100.0; // 保留两位小数
    }

    public static void main(String[] args) {
        DayDataCreateService service = new DayDataCreateService(null, null, null);
        UserInfoDayEntity day = new UserInfoDayEntity();
        service.timeAndCreate(day);

        System.out.println("入睡时间: " + day.getSleepTime());
        System.out.println("起床时间: " + day.getWakeupTime());
        System.out.println("深睡比例: " + day.getDeepSleepPercentage() + "%");
        System.out.println("REM睡眠比例: " + day.getRemSleepPercentage() + "%");
        System.out.println("浅睡比例: " + day.getLightSleepPercentage() + "%");
    }
}